//
//  IWHttpTool.m
//  ItcastWeibo
//
//  Created by apple on 14-5-19.
//  Copyright (c) 2014年 itcast. All rights reserved.
//

#import "IWHttpTool.h"
#import "YbrEmpty.h"
#import "MKNetworkKit.h"
#import "NSString+Ybr.h"
#import "AFHTTPRequestOperation.h"
#import "YbrJsonUtil.h"
#import "AFHTTPRequestOperationManager.h"

static NSDictionary *errMap;

@implementation IWHttpTool


- (instancetype)init
{
    self = [super init];
    if (self) {
        
        [errMap retain];
    }
    return self;
}




+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
//    // 1.创建请求管理对象
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//    
//    // 2.发送请求
//    [mgr POST:url parameters:params
//      success:^(AFHTTPRequestOperation *operation, id responseObject) {
//          if (success) {
//              success(responseObject);
//          }
//      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//          if (failure) {
//              failure(error);
//          }
//      }];
    

   
    
    if([NSString isEmpty:url]) {
        NSLog(@"POst请求的时候请求的参数是null");
        failure(nil);
        return;
    }
    
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
    
    MKNetworkOperation *op = [engine operationWithURLString:url params:params httpMethod:@"POST"];
    [op onCompletion:^(MKNetworkOperation *operation) {
//        NSLog(@"传递回来的  === %@" ,[op responseJSON]);
        id responseObject = [op responseJSON];
        success(responseObject);
    } onError:^(NSError *error) {
        NSString *errContent = nil;
        if([[error localizedDescription] isEqualToString:@"Could not connect to the server."]) {
            errContent = NoNet;
        }else {
            errContent = HTTPFAIL;
        }
        failure(errContent);
    }];
    [engine enqueueOperation:op];
}

+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params formDataArray:(NSArray *)formDataArray success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
//    // 1.创建请求管理对象
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//    
//    // 2.发送请求
//    [mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> totalFormData) {
//        for (IWFormData *formData in formDataArray) {
//            [totalFormData appendPartWithFileData:formData.data name:formData.name fileName:formData.filename mimeType:formData.mimeType];
//        }
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        if (success) {
//            success(responseObject);
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        if (failure) {
//            failure(error);
//        }
//    }];
    
}

+(void) getWithURLWithXMLY:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSString *))failure
{
    NSMutableDictionary *mutable = [NSMutableDictionary dictionaryWithDictionary:params];
    [mutable setObject:XMLY_UserInfo forKey:@"i_am"];
    [mutable setObject:[[UIDevice currentDevice].identifierForVendor UUIDString] forKey:@"uni"];
    params = mutable;
    
//    NSLog(@"请求的链接是 --  %@  %@" ,url ,params);
    
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
    
    
    MKNetworkOperation *op = [engine operationWithURLString:url params:params httpMethod:@"GET"];
    [op onCompletion:^(MKNetworkOperation *operation) {
//        NSLog(@"传递回来的  === %@" ,[operation responseJSON]);
        YbrLog(@"%@",operation.readonlyRequest.URL);
        id responseObject = [operation responseJSON];
        
        success(responseObject);
        
    } onError:^(NSError *error) {
        NSString *errContent = nil;
        if([[error localizedDescription] isEqualToString:@"Could not connect to the server."]) {
            errContent = NoNet;
        }else {
            errContent = HTTPFAIL;
        }
        failure(errContent);
    }];
    [engine enqueueOperation:op];
    
}

+ (void)getWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSString *))failure
{
    errMap = [NSDictionary dictionaryWithObjectsAndKeys:
              @"请求失败" ,           @"0",
              @"请求成功" ,           @"1",
              @"用户名不能为空" ,      @"2",
              @"密码不能为空" ,        @"3",
              @"此用户名不存在" ,      @"4",
              @"密码错误" ,           @"5",
              @"登陆成功" ,           @"6",
              @"登陆失败,请稍后再试" ,  @"7",
              @"此用户名已存在" ,      @"8",
              @"注册成功" ,           @"9",
              @"注册失败,请稍后再试" , @"10",
              @"手机格式错误" ,       @"11",
              @"非法参数" ,          @"12",
              @"参数为空" ,          @"13",
              @"密码为空" ,          @"14",
              @"前后注册用户不同" ,   @"15",
              @"前后密码不同" ,       @"16",
              @"验证码为空" ,        @"17",
              @"验证码匹配错误" ,     @"18",
              @"密码为空" ,          @"19",
              @"用户未登陆" ,        @"20",
              @"手机号为空" ,        @"21",
              @"SN码为空" ,         @"22",
              @"SN码不存在" ,       @"23",
              @"数量超过限制默认数量" ,@"24",
              @"手机设备id为空	" ,    @"25",
              @"删除成功" ,         @"26",
              @"删除失败" ,         @"27",
              @"无此记录" ,         @"28",
              @"该分类只有VIP用户才能添加课程" ,  @"32",
              @"该分类不能添加课程" ,            @"33",
              @"已存在该记录" ,                 @"34",
              @"操作频繁" ,                     @"40",
              @"一个小时内只能发2次" ,            @"41",
              nil];
    
    [errMap retain];
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
    MKNetworkOperation *op  = [engine operationWithURLString:url params:params httpMethod:@"GET"];
    
    [op onCompletion:^(MKNetworkOperation *operation)
    {
        YbrLog(@"%@",operation.readonlyRequest.URL);
        // NSLog(@"传递回来的  === %@" ,[op responseJSON]);
        
        id responseObject   =   [op responseJSON];
        NSNumber *status    =   responseObject[@"status"];
        
        
        NSLog(@"-----获取信息--------%@",[errMap objectForKey:status.stringValue]);
        
        
        if(!(status.intValue == 1))
        {
            if(status.intValue == 24)
            {
                success([NSString stringWithFormat:@"err%@" ,[YbrJsonUtil ToSystemJson:responseObject[@"status"]]]);
//                return;
            }
            success([errMap objectForKey:status.stringValue]);
//            return;
        }else{
            if(responseObject[@"data"] == nil || [[NSString stringWithFormat:@"%@" ,responseObject[@"data"]] length] == 0) {
                success([[YbrEmpty alloc] init]);
//                return;
            }
            success(responseObject[@"data"]);
        }
    } onError:^(NSError *error)
    {
        NSString *errContent = nil;
        if([[error localizedDescription] isEqualToString:@"Could not connect to the server."])
        {
            errContent = NoNet;
        }else {
            errContent = HTTPFAIL;
        }
        failure(errContent);
    }];
    [engine enqueueOperation:op];
}


+ (void)getWithURLWithCourse:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure
{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 发送get请求
    [mgr GET:url parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject){
         if (success)
         {
             success(responseObject);
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error){
         if (failure)
         {
             failure(error);
         }
     }];
}


/**
 *  @author Jakey
 *  @brief  下载文件
 *  @param paramDic   附加post参数
 *  @param requestURL 请求地址
 *  @param savedPath  保存 在磁盘的位置
 *  @param success    下载成功回调
 *  @param failure    下载失败回调
 *  @param progress   实时下载进度回调
 */
+(void)downloadFileWithOption:(NSDictionary *)paramDic
                 withInferface:(NSString*)requestURL
                     savedPath:(NSString*)savedPath
               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      progress:(void (^)(float progress))progress

{
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURL parameters:paramDic error:nil];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p = (float)totalBytesRead / totalBytesExpectedToRead;
        progress(p);
        
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation,responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        success(operation,error);
    }];
    
    [operation start];
    
}
@end


// 用来封装文件数据的模型
@implementation IWFormData

@end
